package com.agileboot.attendance.domain.settlement.model;

import com.agileboot.attendance.domain.settlement.dto.SettlementQuery;
import com.agileboot.attendance.domain.settlement.entity.AttSettlementEntity;
import com.agileboot.attendance.domain.settlement.db.service.AttSettlementService;
import com.agileboot.common.core.page.PageDTO;
import com.agileboot.common.exception.ApiException;
import com.agileboot.common.exception.error.ErrorCode;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 结算单模型工厂
 */
@Component
@RequiredArgsConstructor
public class SettlementModelFactory {

    @Resource
    private AttSettlementService settlementService;

    /**
     * 创建新的结算单模型
     */
    public SettlementModel create() {
        return new SettlementModel(new AttSettlementEntity());
    }

    /**
     * 根据ID加载结算单模型
     */
    public SettlementModel loadById(Long settlementId) {
        AttSettlementEntity entity = settlementService.getById(settlementId);
        if (entity == null) {
            throw new ApiException(ErrorCode.Business.COMMON_OBJECT_NOT_FOUND, "结算单");
        }
        return new SettlementModel(entity);
    }

    /**
     * 分页查询结算单
     */
    public PageDTO<SettlementModel> selectPage(SettlementQuery query) {
        Page<AttSettlementEntity> page = settlementService.queryPage(query);
        List<SettlementModel> models = page.getRecords().stream()
            .map(entity -> new SettlementModel(entity))
            .collect(Collectors.toList());
        
        PageDTO<SettlementModel> pageDTO = new PageDTO<>();
        pageDTO.setRows(models);
        pageDTO.setTotal(page.getTotal());
        pageDTO.setPageNum(page.getCurrent());
        pageDTO.setPageSize(page.getSize());
        return pageDTO;
    }
} 